import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:get/get_rx/src/rx_workers/utils/debouncer.dart';
import 'package:sainbainu/common/apis/common_api.dart';
import 'package:sainbainu/common/http/exception.dart';
import 'package:sainbainu/common/models/response/area_list_response.dart';
import 'package:sainbainu/common/repositories/common_repository.dart';
import 'package:sainbainu/common/utils/loading.dart';
import 'package:sainbainu/common/widgets/cancel_confirm_wrapper.dart';

enum AreaType {
  province,
  city,
  county,
}

typedef AreaCallBack = void Function(
  AreaItemResponse province,
  AreaItemResponse? city,
  AreaItemResponse? county,
);

class RegionPickerDialog extends StatefulWidget {
  final VoidCallback? onCancelTap;
  final AreaCallBack? onConfirmTap;

  const RegionPickerDialog({super.key, this.onCancelTap, this.onConfirmTap});

  @override
  State<RegionPickerDialog> createState() => _RegionPickerDialogState();
}

class _RegionPickerDialogState extends State<RegionPickerDialog> {
  /// 滚动选择器防抖
  late Debouncer _debouncerPicker1;
  late Debouncer _debouncerPicker2;
  late Debouncer _debouncerPicker3;

  late CommonRepository _commonRepository;
  AreaListResponse _provinceList = AreaListResponse(list: []);
  AreaListResponse _cityList = AreaListResponse(list: []);
  AreaListResponse _countyList = AreaListResponse(list: []);
  int _provinceIndex = 0;
  int _cityIndex = 0;
  int _countyIndex = 0;

  @override
  void initState() {
    super.initState();
    _debouncerPicker1 = Debouncer(delay: const Duration(milliseconds: 800));
    _debouncerPicker2 = Debouncer(delay: const Duration(milliseconds: 800));
    _debouncerPicker3 = Debouncer(delay: const Duration(milliseconds: 800));
    _commonRepository = CommonRepository(CommonApi());
    Future.delayed(const Duration(milliseconds: 400)).then(
      (_) => getProvinceList(),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _debouncerPicker1.cancel();
    _debouncerPicker2.cancel();
    _debouncerPicker3.cancel();
  }

  /// 获取地区数据
  Future<void> getAreaList({
    String? pid,
    required AreaType areaType,
  }) async {
    if (pid == null) {
      return LoadingUtil.showError('缺少必要参数');
    }
    AreaListResponse res = await _commonRepository.areaList(pid);
    if (areaType == AreaType.province) {
      _provinceList = res;
    } else if (areaType == AreaType.city) {
      _cityList = res;
    } else if (areaType == AreaType.county) {
      _countyList = res;
    }
    setState(() {});
  }

  /// 获取省份数据
  Future<void> getProvinceList() async {
    try {
      LoadingUtil.showLoading(text: '加载中');
      await getAreaList(pid: '0', areaType: AreaType.province);
      await getCityList();
      await getCountyList();
      LoadingUtil.dismiss();
    } on CustomHttpException catch (e) {
      LoadingUtil.showError(e.message);
    } catch (e) {
      LoadingUtil.showError('获取地区数据失败');
    }
  }

  /// 获取市数据
  Future<void> getCityList() async {
    String? pid = _provinceList.list[_provinceIndex].value;
    await getAreaList(pid: pid, areaType: AreaType.city);
  }

  /// 获取区数据
  Future<void> getCountyList() async {
    String? pid = _cityList.list[_cityIndex].value;
    await getAreaList(pid: pid, areaType: AreaType.county);
  }

  /// 选择省份
  void onProvinceItemChanged(int index) {
    _debouncerPicker1(() async {
      _provinceIndex = index;
      // 获取市\区数据
      try {
        LoadingUtil.showLoading(text: '加载中');
        await getCityList();
        await getCountyList();
        LoadingUtil.dismiss();
      } on CustomHttpException catch (e) {
        LoadingUtil.showError(e.message);
      } catch (e) {
        LoadingUtil.showError('获取地区数据失败');
      }
    });
  }

  /// 选择城市
  void onCityItemChanged(int index) {
    _debouncerPicker2(() async {
      _cityIndex = index;
      // 获取区数据
      try {
        LoadingUtil.showLoading(text: '加载中');
        await getCountyList();
        LoadingUtil.dismiss();
      } on CustomHttpException catch (e) {
        LoadingUtil.showError(e.message);
      } catch (e) {
        LoadingUtil.showError('获取地区数据失败');
      }
    });
  }

  /// 选择区
  void onCountyItemChanged(int index) {
    _debouncerPicker3(() {
      _countyIndex = index;
    });
  }

  /// 地区确认选择
  void onConfirm() {
    if (widget.onConfirmTap != null) {
      if (_provinceList.list.isEmpty) {
        return;
      }
      widget.onConfirmTap!(
        _provinceList.list[_provinceIndex],
        _cityList.list.isEmpty ? null : _cityList.list[_cityIndex],
        _countyList.list.isEmpty ? null : _countyList.list[_countyIndex],
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return CancelConfirmWrapper(
      titleText: '${'设置'.tr}${'所在地'.tr}',
      onCancelTap: widget.onCancelTap,
      onConfirmTap: onConfirm,
      child: Row(
        children: [
          Expanded(
            child: _buildPickerView(
              onChanged: onProvinceItemChanged,
              areaList: _provinceList,
            ),
          ),
          Expanded(
            child: _buildPickerView(
              onChanged: onCityItemChanged,
              areaList: _cityList,
            ),
          ),
          Expanded(
            child: _buildPickerView(
              onChanged: onCountyItemChanged,
              areaList: _countyList,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建滚动选择器
  _buildPickerView({
    required void Function(int) onChanged,
    required AreaListResponse areaList,
  }) {
    return CupertinoPicker(
      itemExtent: 44,
      onSelectedItemChanged: onChanged,
      children: areaList.list
          .map(
            (item) => Container(
              alignment: Alignment.center,
              padding: const EdgeInsets.symmetric(horizontal: 8),
              child: Text(
                item.text,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                textAlign: TextAlign.center,
                style: const TextStyle(fontSize: 17),
              ),
            ),
          )
          .toList(),
    );
  }
}
